package com.zcx.qshop.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.zcx.qshop.QSApplication;

public class SideBar extends View{

	private String[] strings = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

	private OnLetterTouchListener letterTouchListener;

	private float itemHeight = -1 ;

	private Paint paint;

	private Bitmap letterBitmap;

	public SideBar(Context context, AttributeSet attrs) {

		super(context, attrs);

	}

	@Override
	protected void onDraw(Canvas canvas){

		if (itemHeight == -1){

			itemHeight = getHeight() / strings.length;

		}

		if (paint == null) {

			paint = new Paint();

			paint.setTextSize(QSApplication.ScaleScreenHelper.getSize(22));

			paint.setColor(Color.parseColor("#111111"));

			paint.setFlags(Paint.ANTI_ALIAS_FLAG);

			Canvas mCanvas = new Canvas();

			letterBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);

			mCanvas.setBitmap(letterBitmap);

			float widthCenter = getMeasuredWidth() / 2.0F;

			for (int i = 0; i < strings.length; i++){

				mCanvas.drawText(strings[i], widthCenter - paint.measureText(strings[i]) / 2, itemHeight * i + itemHeight, paint);

			}

		}

		if (letterBitmap != null) canvas.drawBitmap(letterBitmap, 0, 0, paint);

		super.onDraw(canvas);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		super.onTouchEvent(event);

		if (letterTouchListener == null){

			return false;

		}

		switch (event.getAction()){

			case MotionEvent.ACTION_DOWN:

			case MotionEvent.ACTION_MOVE:

				int position = (int) (event.getY() / itemHeight);

				if (position >= 0 && position < strings.length){

					letterTouchListener.onLetterTouch(strings[position], position);

				}

				return true;

			case MotionEvent.ACTION_OUTSIDE:

			case MotionEvent.ACTION_UP:

				letterTouchListener.onActionUp();

				return true;

		}

		return false;

	}

	public void setOnLetterTouchListener(OnLetterTouchListener listener){

		this.letterTouchListener = listener;

	}

	public interface OnLetterTouchListener {

		public void onLetterTouch(String letter, int position);

		public void onActionUp();

	}

}
